package com.elminster.common.db.analyze;

import java.lang.reflect.Field;

import com.elminster.common.db.annotation.KeyPolicy;
import com.elminster.common.db.exception.SqlAnalyzeException;
import com.elminster.common.util.ReflectUtil;

public class ORMInsertAnalyzer extends ORMSqlAnalyzer {
	
	@Override
	public SqlType getSqlType() {
		return SqlType.UPDATE;
	}

	@Override
	protected void mapping(Object obj) {
		StringBuilder builder = new StringBuilder();
		
		builder.append("INSERT INTO ");
		builder.append(getTableName(obj));
		builder.append(" (");
		Field[] fields = ReflectUtil.getAllField(obj.getClass());
		boolean first = true;
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			if (isKey(field)) {
				KeyPolicy keyPolicy = getKeyPolicy(field);
				// auto inc policy is not necessary to set the key
				if (KeyPolicy.AUTO_INC_POLICY == keyPolicy) {
					continue;
				}
			}
			if (isColumn(field)) {
				if (!first) {
					builder.append(", ");
				} else {
					first = false;
				}
				builder.append(getColumnName(field));
			}
			try {
				analyzedSqlParameters.add(ReflectUtil.getFieldValue(obj, field));
			} catch (IllegalArgumentException e) {
				throw new SqlAnalyzeException(e);
			} catch (IllegalAccessException e) {
				throw new SqlAnalyzeException(e);
			}
		}
		builder.append(") VALUES (");
		for (int i = 0; i < analyzedSqlParameters.size(); i++) {
			if (0 != i) {
				builder.append(", ");
			}
			builder.append("?");
		}
		builder.append(")");
		analyzedSql = builder.toString();
	}
}
